#!/bin/bash

set -e

# CPU architecture:ARCH="amd64"、ARCH="arm64"
ARCH="amd64"
# Debian release version
DEBIAN_RELEASE="bookworm"
# Debian mirror URL
#MIRROR="http://deb.debian.org/debian"
MIRROR="http://mirrors.aliyun.com/debian"
# Target directory
TARGET_DIR=$(dirname "$(pwd)")
echo "builder target dir: ${TARGET_DIR}"
# RootFS directory
ROOTFS_DIR="${TARGET_DIR}/sys_rootfs"
# CPU architecture:ARCH="amd64"、ARCH="arm64"
ARCH="amd64"
# Debian kernel version
KERNEL_VERSION="6.1.0-35-${ARCH}"
# RootFS version
ROOTFS_VERSION="1.0.0-${ARCH}"
# RootFS name
ROOTFS_NAMR="rootfs-${ROOTFS_VERSION}.tar.gz"
# backup orginal rootfs
POOL_DIR="${TARGET_DIR}/pool"

echo "Start Build RootFS..."
# Check build tools
REQUIRED_TOOLS=("parted" "debootstrap")
for tool in "${REQUIRED_TOOLS[@]}"; do
    if ! command -v "$tool" &> /dev/null; then
        echo "install tools: $tool..."
        apt update && apt install -y "$tool"
    fi
done

# Create RootFS
if [ -d ${ROOTFS_DIR} ]; then
    echo "Remove Old RootFS..."
    rm -rf ${ROOTFS_DIR}    
fi
mkdir -p ${ROOTFS_DIR}

echo "Start debootstrap Debian ${DEBIAN_RELEASE}_${ARCH}..."

cd ${ROOTFS_DIR}
debootstrap --arch=${ARCH} ${DEBIAN_RELEASE} ${ROOTFS_DIR} ${MIRROR}
echo "Finish debootstrap Debian ${DEBIAN_RELEASE}_${ARCH}..."

echo "Chroot Start RootFS Config..."

chroot "$ROOTFS_DIR" /bin/bash <<EOF
# configure sources.list
echo "configure sources.list..."
cat > /etc/apt/sources.list <<SOURCES
deb $MIRROR $DEBIAN_RELEASE main contrib non-free
deb-src $MIRROR $DEBIAN_RELEASE main contrib non-free

deb $MIRROR $DEBIAN_RELEASE-updates main contrib non-free
deb-src $MIRROR $DEBIAN_RELEASE-updates main contrib non-free

deb $MIRROR-security $DEBIAN_RELEASE-security main contrib non-free
deb-src $MIRROR-security $DEBIAN_RELEASE-security main contrib non-free
SOURCES

# install basic packages
echo "install basic packages..."
apt update
apt install -y linux-image-${KERNEL_VERSION} systemd-sysv grub2 network-manager openssh-server sudo util-linux locales
apt install -y parted dosfstools cryptsetup
apt install -y pciutils usbutils dmidecode hwinfo ethtool net-tools

# configure locale
echo "configure locale..."
echo 'LANG=en_US.UTF-8' > /etc/default/locale
sed -i 's/^# en_US.UTF-8/en_US.UTF-8/' /etc/locale.gen
locale-gen

# configure timezone
echo "configure timezone..."
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
echo 'Asia/Shanghai' > /etc/timezone
dpkg-reconfigure -f noninteractive tzdata

# configure hosts
echo "configure hosts..."
cat > /etc/hosts <<HOSTS
127.0.0.1       localhost
127.0.0.1       DevServer
::1             localhost ip6-localhost ip6-loopback
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters
HOSTS

# configure GRUB
echo "configure GRUB..."
sed -i \
  -e 's/^GRUB_CMDLINE_LINUX_DEFAULT=.*/GRUB_CMDLINE_LINUX_DEFAULT=\"quiet splash\"/' \
  -e 's/^GRUB_CMDLINE_LINUX=.*/GRUB_CMDLINE_LINUX=\"net.ifnames=0 biosdevname=0\"/' \
  /etc/default/grub

# configure root password
echo "configure root password..."
echo 'root:root' | chpasswd
echo -e '\nexport PATH=$PATH:/usr/sbin:/sbin:/root/.local/bin' >> /root/.bashrc

# create user develop
echo "create user develop..."
useradd -m -s /bin/bash -G sudo develop
echo 'develop:develop' | chpasswd
echo 'develop ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers
echo 'Defaults visiblepw' >> /etc/sudoers
echo 'Defaults secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"' >> /etc/sudoers
echo -e '\nexport PATH=$PATH:/usr/sbin:/sbin' >> /home/develop/.bashrc

# remove unnecessary packages
echo "remove unnecessary packages..."
apt autoremove -y
apt clean
# clean cache
echo "clean cache..."
rm -rf /var/cache/*
rm -rf /var/lib/apt/lists/*
# clean temporary files
echo "clean temporary files..."
rm -rf /tmp/*
rm -rf /var/tmp/*  
# clean log files
echo "clean log files..."
find /var/log -type f -name "*.log" -exec rm -f {} \;
find /var/log -type f -name "*.gz" -exec rm -f {} \;
EOF

echo "Chroot Finish Basic Config..."

# backup rootfs
# clean pool dir
if [ ! -d ${POOL_DIR} ]; then
    mkdir -p ${POOL_DIR}
fi
# clean old rootfs
if [ -f ${POOL_DIR}/${ROOTFS_NAMR} ]; then
    echo "Remove old ${ROOTFS_NAMR} ..."
    rm -f ${POOL_DIR}/${ROOTFS_NAMR}   
fi
# package rootfs edisk
echo "Package ${ROOTFS_NAMR} ..."
cd ${ROOTFS_DIR}
tar -czf ${POOL_DIR}/${ROOTFS_NAMR} .
echo "Package ${ROOTFS_NAMR} is created at ${POOL_DIR}/${ROOTFS_NAMR}"

echo "Finish Build RootFS..."
